package handlers

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"user-h2/api/request"
	"user-h2/inits"
)

func WsFunc(context *gin.Context) {
	upgrader := websocket.Upgrader{}
	c, err := upgrader.Upgrade(context.Writer, context.Request, nil)
	if err != nil {
		log.Println("upgrade", err)
		return
	}
	defer c.Close()
	for {
		_, message, err := c.ReadMessage()
		if err != nil {
			log.Println("read", err)
			break
		}
		var req request.WsRep

		err = json.Unmarshal(message, &req)
		if err != nil {
			RespError(c, 500, "非法参数")
			return
		}
		switch req.Cmd {
		case "online":
			go OnlineFunc(c, message)
		case "send":
			go SendFunc(c, message)
		case "allSend":
			go AllSend(c, message)
		default:
			go RespError(c, 500, "没有该方法")
		}

	}
}

func AllSend(c *websocket.Conn, message []byte) {
	var req request.WqAllSendReq
	err := json.Unmarshal(message, &req)
	if err != nil {
		RespError(c, 500, "解析群发消息请求失败")
		return
	}
	for userId, _ := range inits.OnlineUser {
		RespSuccess(inits.OnlineUser[userId], req.Data.Message)
	}
}

func SendFunc(c *websocket.Conn, message []byte) {
	var req request.WSSendReq
	err := json.Unmarshal(message, &req)
	if err != nil {
		RespError(c, 500, "解析相互发送消息失败")
		return
	}
	conn := inits.OnlineUser[req.Data.ToUserID]
	if conn == nil {
		RespError(c, 500, "用户不在线")
		return
	}
	RespSuccess(conn, req.Data.Message)
	RespSuccess(c, "发送消息ok")
}

func OnlineFunc(c *websocket.Conn, message []byte) {
	var req request.WsOnlineReq
	err := json.Unmarshal(message, &req)
	if err != nil {
		RespError(c, 500, "online请求解析错误")
		return
	}
	fmt.Println(req)
	inits.OnlineUser[req.Data.UserId] = c
	fmt.Println(inits.OnlineUser)
	RespSuccess(c, "成功")

}

func RespError(c *websocket.Conn, code int, msg string) {
	resp := request.WsResp{
		Code: code,
		Msg:  msg,
	}
	marshal, err := json.Marshal(resp)
	err = c.WriteMessage(websocket.TextMessage, marshal)
	if err != nil {
		log.Println("write:", err)
	}
}

func RespSuccess(c *websocket.Conn, data interface{}) {
	resp := request.WsResp{
		Code: 200,
		Msg:  "ok",
		Data: data,
	}
	marshal, err := json.Marshal(resp)
	err = c.WriteMessage(websocket.TextMessage, marshal)
	if err != nil {
		log.Println("write:", err)
	}
}
